package util.web;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import authority.Authority;
import role.Role;
import role.RoleDao;
import user.User;
public class AuthorityFilter implements Filter{
	private Role role=new Role(); 
	private RoleDao roledao;
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpServletRequest request = (HttpServletRequest)servletRequest;
		String url = request.getServletPath();
		if(request.getSession().getAttribute("user")==null){
			ApplicationContext ctx = new FileSystemXmlApplicationContext("src\\main\\webapp\\WEB-INF\\applicationContext.xml"); 
			roledao=(RoleDao) ctx.getBean("roleDao");
			this.role=roledao.findById(1L);
			System.out.println("是什么角色:"+this.role.getRole_name());
			System.out.println(this.role.getRole_authority().size());
			Iterator<Authority> it =this.role.getRole_authority().iterator();
			while(it.hasNext()){
				Authority authority=(Authority) it.next();
				if(url.endsWith(authority.getAuthority_url_no())){
					System.out.println("youke:"+authority.getAuthority_url_no());
					System.out.println("获得的路径:"+url);
					request.getSession().setAttribute("message","您的权限不足，请登陆！谢谢！");
					response.sendRedirect("/jiae/enterlogin.action");
				}
			}
			filterChain.doFilter(servletRequest, servletResponse);
		}else{
			User user=(User) request.getSession().getAttribute("user");
			System.out.println("user是什么角色:"+user.getUser_role().iterator().next().getRole_name());
			Iterator<Authority> it=user.getUser_role().iterator().next().getRole_authority().iterator();
			System.out.println("user不可访问的有几个:"+user.getUser_role().iterator().next().getRole_authority().size());
			while(it.hasNext()){
				Authority authority=(Authority) it.next();
				if(url.endsWith(authority.getAuthority_url_no())){
					System.out.println("user不可访问的:"+authority.getAuthority_url_no());
					System.out.println("user获得的路径:"+url);
					request.getSession().setAttribute("message","您的权限不足，请联系我们申请更多功能。谢谢！");
					response.sendRedirect("/jiae/enterlogin.action");
				}
			}
			filterChain.doFilter(servletRequest, servletResponse);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
